package com.example.litterpainterdemo.home

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.example.litterpainterdemo.db.Picture
import com.example.litterpainterdemo.databinding.PictureItemBinding


class PictureAdapter:RecyclerView.Adapter<PictureAdapter.PictureHolder>() {
    private var pictures = emptyList<Picture>()

    //传递数据源
    @SuppressLint("NotifyDataSetChanged")
    fun setData(pic:List<Picture>){
        pictures = pic
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PictureHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = PictureItemBinding.inflate(inflater,parent,false)
        return PictureHolder(binding)
    }

    override fun getItemCount(): Int {
        return pictures.size
    }

    override fun onBindViewHolder(holder: PictureHolder, position: Int) {
        holder.bind(pictures[position])
    }

    inner class PictureHolder(private val binding:PictureItemBinding):RecyclerView.ViewHolder(binding.root){
        fun bind(pic: Picture){
            binding.imageView.setImageBitmap(pic.thumbnail)
            binding.imageView.setOnClickListener {
                //跳转到绘制页面
                val action = HomeFragmentDirections.actionHomeFragmentToDrawFragment(pic)
                binding.imageView.findNavController().navigate(action)
            }
        }
    }


}